package com.saas.ability.gateway.filter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.saas.ability.gateway.base.protocol.input.ReqHeaderInput;
import com.netflix.zuul.context.RequestContext;

/**
 * 请求访问进入
 *
 */
@Component
public class AccessFilter extends AbstractFilter {
	
	Logger logger = LoggerFactory.getLogger(AccessFilter.class);

	@Override
	public boolean shouldFilter() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		String requestURI = request.getRequestURI();
		//是否验证版本
		ctx.set(VERIFY_VERSION,isVerifyVersion(requestURI));
		//是否验证token
		ctx.set(VERIFY_TOKEN,isVerifyToken(requestURI));
		return true;
	}
	
	/**
	 * 需要验证版本的请求
	 * @param requestURI
	 * @return
	 */
	private boolean isVerifyVersion(String requestURI){
		//满足这个正则的uri不校验版本号
		String regex = "(/version/).*";
        Matcher m = Pattern.compile(regex).matcher(requestURI);
        return !m.find();
	}
	
	/**
	 * 需要验证登录token的请求
	 * @param requestURI
	 * @return
	 */
	private boolean isVerifyToken(String requestURI){
        return true;
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		String contextPath = request.getContextPath();
		String uri = request.getRequestURI();
		String queryString = request.getQueryString();
		String method = request.getMethod();
		ReqHeaderInput header = parseReqHeader(ctx);
		logger.debug("method:{}:{}:{};queryString:{};header:{}",
				method,contextPath,uri,queryString,header);
		return null;
	}

	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return Integer.MIN_VALUE;
	}
}
